package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.StringUtil;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freemarkerConfig;
    @Value("${out_put_path}")//从属性文件读取输出目录的路径
    private String outputpath;


    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml() {
        List<Setmeal> setmealList = findSetmealList();

        String templateName = "mobile_setmeal.ftl";
        String htmlPageName = "m_setmeal.html";
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        generateHtml(templateName, htmlPageName, dataMap);
    }

    //生成套餐详情静态页面（单个）
    public void generateMobileSetmealDetailHtml(Integer setmealId) {
        Setmeal setmeal = getSetmeal(setmealId);
        String templateName = "mobile_setmeal_detail.ftl";
        String htmlPageName = "setmeal_detail_" + setmeal.getId() + ".html";
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmeal", setmeal);
        generateHtml(templateName, htmlPageName, dataMap);
    }

    //删除套餐详情静态页面（单个）
    public void deleteMobileSetmealDetailHtml(Integer setmealId) {
        File file = new File(outputpath + "setmeal_detail_" + setmealId + ".html");
        file.delete();
    }

    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml() {
        List<Setmeal> setmeals = findSetmealList();
        for (Setmeal setmeal : setmeals) {
            generateMobileSetmealDetailHtml(setmeal.getId());
        }
    }

    /**
     * 生成静态页面
     *
     * @param templateName 模板名
     * @param htmlPageName 生成的HTML文件名
     * @param dataMap      所需的数据
     */
    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        Configuration configuration = freemarkerConfig.getConfiguration();
        File docFile = new File(outputpath + htmlPageName);
        BufferedWriter bw = null;
        try {
            Template template = configuration.getTemplate(templateName);
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            template.process(dataMap, bw);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Result findById(Integer id) {
        Setmeal setmeal = setmealMapper.findById(id);
        setmeal.setImg(setmeal.getImg().split(",")[0]);
        List<CheckGroup> groups = checkGroupMapper.findAll();
        List<Integer> groupsIds = setmealMapper.findGroupsIdsBySetmealId(id);
        setmeal.setCheckGroups(groups);
        setmeal.setCheckGroupIds(groupsIds);
        return Result.success(MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
    }

    @Override
    public Result update(Setmeal setmeal) {
        String oldImg = setmealMapper.findById(setmeal.getId()).getImg();

        setmealMapper.update(setmeal);
        deleteDBData(setmeal, oldImg);

        setmealMapper.deleteCheckGroupIdsBySetmealId(setmeal.getId());
        addSetmealAndCheckGroup(setmeal);

        Jedis jedis = jedisPool.getResource();
        try {
            jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg().split(",")[0]);
            jedis.hset("imgMD5", setmeal.getImg().split(",")[1], setmeal.getImg());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        generateMobileSetmealListHtml();
        generateMobileSetmealDetailHtml(setmeal.getId());
        deleteDBSetmeal();
        return Result.success(MessageConstant.EDIT_SETMEAL_SUCCESS, null);
    }

    @Override
    public Result deleteById(Integer id) {
        setmealMapper.deleteById(id);
        setmealMapper.deleteCheckGroupAndSetmeal(id);
        Setmeal setmeal = setmealMapper.findById(id);

        deleteDBData(setmeal, setmeal.getImg());

        generateMobileSetmealListHtml();
        deleteMobileSetmealDetailHtml(id);
        deleteDBSetmeal();
        return Result.success(MessageConstant.DELETE_SETMEAL_SUCCESS, null);
    }

    @Override
    public Result findAll() {
        List<Setmeal> list = findSetmealList();
        if (list == null) {
            return Result.fail(MessageConstant.GET_SETMEAL_LIST_FAIL);
        }
        return Result.success(MessageConstant.GET_SETMEAL_LIST_SUCCESS, list);
    }

    public List<Setmeal> findSetmealList() {
        Jedis jedis = jedisPool.getResource();
        String setmealAll = jedis.get("setmealAll");
        List<Setmeal> list = null;
        try {
            if (StringUtil.isEmpty(setmealAll)) {
                System.out.println("从数据库获取数据");
                list = setmealMapper.findAll();
                jedis.setex("setmealAll", 60, JSON.toJSONString(list));
            } else {
                System.out.println("从redis获取数据");
                list = JSON.parseArray(setmealAll, Setmeal.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        if (list != null) {
            for (Setmeal setmeal : list) {
                String img = MessageConstant.HOST + setmeal.getImg().split(",")[0];
                setmeal.setImg(img);
            }
        }
        return list;
    }

    @Override
    public Result findSetmealById(Integer id) {
        Setmeal setmeal = getSetmeal(id);
        return Result.success(MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
    }

    public Setmeal getSetmeal(Integer id) {
        Setmeal setmeal = setmealMapper.findSetmealById(id);
        String img = MessageConstant.HOST + setmeal.getImg().split(",")[0];
        setmeal.setImg(img);
        return setmeal;
    }

    @Override
    public Result add(Setmeal setmeal) {
        setmealMapper.save(setmeal);
        addSetmealAndCheckGroup(setmeal);

        Jedis jedis = jedisPool.getResource();
        try {
            jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg().split(",")[0]);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        generateMobileSetmealListHtml();
        generateMobileSetmealDetailHtml(setmeal.getId());
        deleteDBSetmeal();
        return Result.success(MessageConstant.ADD_SETMEAL_SUCCESS, null);
    }

    @Override
    public Result findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealMapper.findPage(queryPageBean.getQueryString());

        generateMobileSetmealListHtml();
        generateMobileSetmealDetailHtml();
        return Result.success(MessageConstant.QUERY_SETMEAL_SUCCESS, new PageResult(page.getTotal(), page.getResult()));
    }

    private void addSetmealAndCheckGroup(Setmeal setmeal) {
        if (setmeal.getCheckGroupIds() != null || setmeal.getCheckGroupIds().size() > 0) {
            for (Integer checkGroupId : setmeal.getCheckGroupIds()) {
                setmealMapper.saveSetmealAndCheckGroup(setmeal.getId(), checkGroupId);
            }
        }
    }

    private void deleteDBData(Setmeal setmeal, String imgName) {
        String s = "%" + imgName.split(",")[1] + "%";
        Integer count = setmealMapper.findByImg(s);
        if (count == 0) {
            Jedis jedis = jedisPool.getResource();
            try {
                jedis.srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, imgName.split(",")[0]);
                jedis.hdel("imgMD5", imgName.split(",")[1]);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                jedis.close();
            }
        }
    }

    private void deleteDBSetmeal(){
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.del("setmealAll");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
    }
}
